package com.cy.ppj.service.product.impl;

import com.cy.ppj.comm.constant.CacheConstants;
import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.comm.utils.JsonObjectMapper;
import com.cy.ppj.dao.mongodb.XyAdmissionLogDao;
import com.cy.ppj.model.ao.product.AdmissionAO;
import com.cy.ppj.model.doc.AdmissionLog;
import com.cy.ppj.model.dto.admission.xy.XyAdmissionDTO;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.product.AdmissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @description: AdmissionServiceImpl
 * @author: Ocean
 * @create: 2018-08-09 10:24
 **/
@Slf4j
@Service
public class XyAdmissionServiceImpl extends BaseService implements AdmissionService {

    @Autowired
    private RestTemplate xyRestTemplate;
    @Value("${admission.xy.url}")
    private String admissionUrl;
    @Value("${admission.xy.appid}")
    private Integer appId;
    @Value("${admission.xy.ver}")
    private String ver;
    @Value("${admission.xy.partner-id}")
    private Integer partnerId;
    @Autowired
    private XyAdmissionLogDao xyAdmissionLogDao;

    @Override
    public AdmissionLog admission(AdmissionAO admissionAO) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        XyAdmissionDTO xyAdmissionDTO = new XyAdmissionDTO();
        BeanUtils.copyProperties(admissionAO, xyAdmissionDTO);
        xyAdmissionDTO.setAppid(appId);
        xyAdmissionDTO.setPartnerId(partnerId);
        xyAdmissionDTO.setVer(ver);

        String json = JsonObjectMapper.toJson(xyAdmissionDTO);
        log.info("小赢准入查询,params -> {}", json);

        HttpEntity<String> request = new HttpEntity<>(json, headers);
        ResponseEntity<String> responseEntity = xyRestTemplate.postForEntity(admissionUrl, request, String.class);
        state(HttpStatus.OK.equals(responseEntity.getStatusCode()), "小赢准入查询失败");

        Map<String, Object> body = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
        log.info("小赢准入查询回调,body -> {}", body);

        Integer errCode = (Integer) body.get("err_code");
        state(Integer.valueOf(0).equals(errCode), body.get("err_msg") + "");

        Map<String, Object> data = (Map) body.get("data");
        Integer id = (Integer) data.get("id");
        String content = (String) data.get("content");

        String message = null;
        Date expiryDate = null;

        switch (id) {
            case 1:
                message = "该客户不能准入小赢产品";
                expiryDate = CommonUtils.addTime(180, Calendar.DAY_OF_YEAR);
                break;

            case 2:
                message = "该客户可以申请小赢产品";
                expiryDate = CommonUtils.addTime(3, Calendar.DAY_OF_YEAR);
                break;

            case 3:
                message = "该客户已有处理中的借款申请，不可以重复申请";
                expiryDate = CommonUtils.addTime(30, Calendar.DAY_OF_YEAR);
                break;

            case 4:
                message = "该客户已有还款中的借款申请，不可以重复申请";
                expiryDate = CommonUtils.addTime(30, Calendar.DAY_OF_YEAR);
                break;

            case 5:
//                message = "无法系统判定该客户是否准入，请咨询超越工作人员";
                message = "该客户申请过小赢产品，且非还款中";
                expiryDate = CommonUtils.addTime(30, Calendar.DAY_OF_YEAR);
                break;

            case 6:
                message = "无法系统判定该客户是否准入，请咨询超越工作人员";
                break;

            case 7:
                message = "今日平台准入查询次数超限，请联系超越工作人员";
                break;

            default:
                message = "未查到查询结果，请联系业务员";
                break;
        }

        state(expiryDate != null, message);

        //保存记录
        Date time = new Date();
        AdmissionLog admissionLog = new AdmissionLog();
        BeanUtils.copyProperties(admissionAO, admissionLog);
        admissionLog.setCreateTime(time);
        admissionLog.setContent(content);
        admissionLog.setMessage(message);
        admissionLog.setExpiryDate(expiryDate);

        return admissionLog;
    }

    @Override
    @CacheEvict(value = CacheConstants.CACHE_VALUE_2H, key = "'queryLogInCache-'+#admissionLog.idNo")
    public void insertLog(AdmissionLog admissionLog) {
        xyAdmissionLogDao.insert(admissionLog);
    }

    @Override
    @Cacheable(value = CacheConstants.CACHE_VALUE_2H, key = "'queryLogInCache-'+#idNo")
    public AdmissionLog queryLogInCache(String idNo) {
        Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "expiryDate"));
        return xyAdmissionLogDao.findByIdNoAndExpiryDateGreaterThan(idNo, new Date(), sort);
    }
}
